package com.wfyn.reggie.common.web.exception;


import com.wfyn.reggie.common.web.domain.Result;
import com.wfyn.reggie.common.web.exception.base.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


@ResponseBody
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})

public class GlobalExceptionHandler {


    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result handleException(SQLIntegrityConstraintViolationException ex)
    {
        if(ex.getMessage().contains("Duplicate entry"))
        {
            String[] split= ex.getMessage().split(" ");
            for (String s : split) {
                System.out.println(s);
            }
            return Result.failure( split[2] + "已存在");

        }


        return Result.failure("服务器错误，请联系管理员");
    }
      @ExceptionHandler(BusinessException.class)
      public Result handleException(BusinessException ex)
    {

        return Result.failure(ex.getMessage());
    }



}
